<?php

class SFC_Error
{
		private static $instance;

		private $oldErrorHandler;

		protected $lastErrorMessage;
		protected $currentErrorMessage;
		
		public $keepErrContext = FALSE;	// Append $errcontext?
		public $translateErrNo = TRUE;	// Translate $errno?

		protected $errorTypes = array (
						E_ERROR			=> 'Error',
						E_WARNING		=> 'Warning',
						E_NOTICE		=> 'Notice',
						E_USER_ERROR	=> 'User Error',
						E_USER_WARNING	=> 'User Warning',
						E_USER_NOTICE	=> 'User Notice',
						E_STRICT		=> 'Strict'
						);

		protected $errorTypesIgnore = array();
		protected $errorLogTypes	= array(0, 1);

		public function __construct()
		{
				$this->oldErrorHandler = set_error_handler(array(&$this, 'newErrorHandler'));
		}
		
		public static function singleton()
		{
			if (!isset(self::$instance)) {
				$c = __CLASS__;
				self::$instance = new $c;
			}
				return self::$instance;
		}

		public function newErrorHandler($errno, $errstr, $errfile, $errline) //, &$errcontext)
		{
				if (in_array($errno, $this->errorTypesIgnore)) {
						return 0;
				}

				$this->lastErrorMessage = $this->currentErrorMessage;
				$this->currentErrorMessage = func_get_args();

				if (empty($this->currentErrorMessage[4]) || $this->keepErrContext == FALSE) {
						unset($this->currentErrorMessage[4]);
				}

				$this->currentErrorMessage[] = time();

				if ($this->translateErrNo == TRUE) {
						isset($this->errorTypes[$errno]) ? $this->currentErrorMessage[0] = $this->errorTypes[$errno] : $this->currentErrorMessage[0] = 'Unknown';
				}

				array_walk($this->errorLogTypes, array($this, 'errorLogHandler'));
		}

		public function errorLogHandler($item, $key)
		{
				$foo = $this->currentErrorMessage;
				unset($foo[5]); // Get rid of the time stamp!

				switch ($item) {
						case 2:
						case 0:
								error_log(implode($foo, '-'), 0);
								break;
						case 1:
								error_log(implode($foo, '-'), 1, ALERT_EMAIL);
								break;
						case 3:
								error_log(implode($food, '-'), 3, LOG_FILE);
				}
				unset($foo);
		}

		public function getLastErrorMessage($segment = 1)
		{
				return $this->lastErrorMessage[$segment];
		}

		public function getCurrentErrorMessage($segment = 1)
		{
				return $this->currentErrorMessage[$segment];
		}

		public function __destruct() {
				unset($this);
		}
}

?>
